const express = require('express');
const router = express.Router();

router.get('/',
    async (req, res, next) => {
        res.locals.filter = {
            ...res.locals.filter,
            Saved: true,
            Deleted: false,
            Freeze: { $exists: false, $ne: true },
        };

        if (req.query.kw) {
            res.locals.filter = {
                ...res.locals.filter,
                $or: [
                    { '提议': { $regex: req.query.kw, $options: 'i' } },
                    { '标题': { $regex: req.query.kw, $options: 'i' } },
                ],
            };
        }

        if (req.query.类型) {
            res.locals.filter = {
                ...res.locals.filter,
                '类型': req.query.类型,
            };
        }

        return next();
    },
    router.FindDocuments('standards_in_dev', false, async (req, res) => {
        for (let doc of res.locals.data.docs) {
            // get comments for each standard
            doc.comments = await res.app.models.forum_comments.countDocuments({
                Board: 'stddev',
                Topic: doc.id,
            });
        }
    }),
);

router.get('/:id',
    async (req, res, next) => {
        res.locals.filter = {
            ...res.locals.filter,
            Saved: true,
            Deleted: false,
            Freeze: { $exists: false, $ne: true },
            id: req.params.id,
        };

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            'CurrentStep',
            '推荐指数',
            '日期',
            
            '标题',
            '范围',
            '英文名',
            '类型',
            '单位',
            '发布日',
            '实施日',
            '废止日',
            '标准号',
            '文件',
            '起草单位',
            '起草人',
            '链接',
            '标委会',

            'Status',
            'Steps',
        ];
        res.locals.options = {
            lean: true
        };

        return next();
    },
    router.FindDocuments('standards_in_dev', false, (req, res) => {
        res.locals.data = res.locals.data.docs[0];

        if (!res.locals.data) return;

        const steps = (res.locals.data.Steps || []).map((s) => {
            if (!s) return undefined;

            return {
                start: s.StartDate,
                end: s.SubmitDate1,
            };
        });

        const currentStep = res.locals.data.CurrentStep || 1;

        res.locals.data.提议日 = steps[1] && steps[1].start;
        res.locals.data.立项日 = currentStep >= 2 && steps[2] && steps[2].start;
        res.locals.data.拟订日 = currentStep >= 3 && steps[3] && steps[3].start;
        res.locals.data.审核日 = currentStep >= 4 && steps[4] && steps[4].start;
        res.locals.data.发布日 = currentStep >= 4 && steps[4] && steps[4].end;

        delete res.locals.data.Steps;

        res.locals.data.日期 = res.locals.data.日期 || res.locals.data.LastUpdateDate;
    }),
);

module.exports = router;
